package com.xywh.dakaqiandao.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xw.repo.XEditText;
import com.xywh.dakaqiandao.R;
import com.xywh.dakaqiandao.di.component.DaggerRegisterComponent;
import com.xywh.dakaqiandao.di.module.RegisterModule;
import com.xywh.dakaqiandao.mvp.contract.RegisterContract;
import com.xywh.dakaqiandao.mvp.presenter.RegisterPresenter;
import com.xywh.dakaqiandao.mvp.ui.entity.Register;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.BASE_URL;
import static com.jess.arms.base.BaseConstants.NAME_SPACE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_REGISTER)
public class RegisterActivity extends BaseActivity<RegisterPresenter> implements RegisterContract.View, EasyPermissions.PermissionCallbacks {


    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.et_xing_ming)
    XEditText etXingMing;
    @BindView(R.id.et_mi_ma)
    XEditText etMiMa;
    @BindView(R.id.et_que_ren_mi_ma)
    XEditText etQueRenMiMa;
    @BindView(R.id.et_shen_fen_zheng_hao)
    XEditText etShenFenZhengHao;
    @BindView(R.id.et_shou_ji_hao)
    XEditText etShouJiHao;
    @BindView(R.id.rb_nan)
    RadioButton rbNan;
    @BindView(R.id.rb_nv)
    RadioButton rbNv;
    @BindView(R.id.main_radiogroup)
    RadioGroup mainRadiogroup;
    @BindView(R.id.img_pai)
    ImageView imgPai;
    @BindView(R.id.login_btn_login)
    Button loginBtnLogin;
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private BottomDialogUtil mBottomDialogUtilShare;
    private String imgStr = "";

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerRegisterComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .registerModule(new RegisterModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_register; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_register));
        PhotoUtil.init(this, new FrescoIniter());

//        getRegisterData();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        if (requestCode == 1) {

        }
    }

    private void getRegisterData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getRegisterData(map);
    }

    @Override
    public void getRegisterDataSuccess(Register entityData) {


    }

    @OnClick({R.id.img_pai, R.id.login_btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_pai:
                if (getPermission()) {
                    shangChuanTouXiang();
                }
                break;
            case R.id.login_btn_login:

                if (TextUtils.isEmpty(getXingMing())) {
                    ArmsUtils.makeText(getContext(), "请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(getMiMa())) {
                    ArmsUtils.makeText(getContext(), "请输入密码");
                    return;
                }
                if (TextUtils.isEmpty(getQueRenMiMa())) {
                    ArmsUtils.makeText(getContext(), "请输入确认密码");
                    return;
                }
                if (!getMiMa().equals(getQueRenMiMa())) {
                    ArmsUtils.makeText(getContext(), "两次密码输入不一致");
                    return;
                }
                if (TextUtils.isEmpty(getShenFenZhengHao())) {
                    ArmsUtils.makeText(getContext(), "请输入身份证号");
                    return;
                }
                if (TextUtils.isEmpty(getShouJiHao())) {
                    ArmsUtils.makeText(getContext(), "请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(imgStr)) {
                    ArmsUtils.makeText(getContext(), "请拍照");
                    return;
                }

                addRegister();

                break;
        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            return false;
        }

    }

    private void shangChuanTouXiang() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(RegisterActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    createMaterialForInstoreAuto(compressedPath);


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(RegisterActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    createMaterialForInstoreAuto(compressedPath);


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(getContext(), root);
        mBottomDialogUtilShare.showDiaolog();

    }

    @NonNull
    private String getXingMing() {
        return etXingMing.getText().toString().trim();
    }

    @NonNull
    private String getMiMa() {
        return etMiMa.getText().toString().trim();
    }

    @NonNull
    private String getQueRenMiMa() {
        return etQueRenMiMa.getText().toString().trim();
    }

    @NonNull
    private String getShenFenZhengHao() {
        return etShenFenZhengHao.getText().toString().trim();
    }

    @NonNull
    private String getShouJiHao() {
        return etShouJiHao.getText().toString().trim();
    }

    /**
     * AddRegister(string employeeName, string employeePassword, string identityCardNo, string telNo, string sex, string image)
     *
     * @param
     */
    private void addRegister() {

        showLoading();

        String methodName = "AddRegister";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("employeeName", getXingMing());
        params.put("employeePassword", getMiMa());
        params.put("identityCardNo", getShenFenZhengHao());
        params.put("telNo", getShouJiHao());
        if (rbNan.isChecked()) {
            params.put("sex", "男");
        }
        if (rbNv.isChecked()) {
            params.put("sex", "女");
        }
        try {
            params.put("image", ArmsUtils.bitmapPathToBase64String(imgStr));
        } catch (Exception e) {
            e.printStackTrace();
        }


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("AddRegisterResult").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("-1") && !result.equals("-2") && !result.equals("-3")) {
                    ArmsUtils.makeText(getContext(), "注册成功");
                    mSharedPreferencesHelper.putString(BaseConstants.IS_SET, "0");
                    killMyself();
                    return;
                } else if (result.equals("-2")) {
                    ArmsUtils.makeText(getContext(), "请勿重复注册");
                    return;
                } else if (result.equals("-3")) {
                    ArmsUtils.makeText(getContext(), "您还不是在职员工！");
                    return;
                } else {
                    ArmsUtils.makeText(getContext(), "注册失败");
                    return;
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    private void createMaterialForInstoreAuto(String compressedPath) throws Exception {
//        imgStr = ArmsUtils.fileToBase64(compressedPath);
        imgStr = compressedPath;
        Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
        imgPai.setImageBitmap(bitmap);
//        HashMap<String, String> map = new HashMap<String, String>();
//        map.put("did", String.valueOf(did));
//        map.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
//        map.put("num", String.valueOf(num));
//        map.put("imgStr", String.valueOf(imgStr));
//
//        mPresenter.createMaterialForInstoreAuto(StorageActivity.this, map);
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

}
